module mpi_wrap

  use dimensions

  implicit none

  include 'mpif.h'


!-- MPI parameters


  ! Uncomment this for the systems that do not have OpenMPI
  ! In OpenMPI, the parameter MPI_INTEGER_KIND is defined in 'mpif.h'
  ! With other MPI implementations, this parameter has to be defined manually.
  !integer MPI_INTEGER_KIND
  !parameter (MPI_INTEGER_KIND = 4)

    
  integer(kind=MPI_INTEGER_KIND) :: myid, npAll, mpi_err, mpi_info

  !integer (kind=MPI_INTEGER_KIND) :: sendtag, recvtag
  !integer (kind=MPI_INTEGER_KIND) :: request, request1, request2, request3, mpi_request

  integer (kind=MPI_INTEGER_KIND) :: mpi_status(MPI_STATUS_SIZE)

  character*120 :: msg



!================================================================================
contains
!================================================================================

  subroutine mpi_wrap_init

    implicit none


    call MPI_INIT(mpi_err)
    call MPI_Comm_size(MPI_COMM_WORLD, npAll, mpi_err)
    call MPI_Comm_rank(MPI_COMM_WORLD, myid,  mpi_err)

    if (npAll .ne. npDir) then
       write(msg,*) "The code is compiled for ", npDir, "processes."
       call mpi_wrap_err
    end if

    write(msg,*) char(10), ' mpi_wrap module initialized'
    call mpi_wrap_msg

    return
  end subroutine mpi_wrap_init

!================================================================================

  subroutine mpi_wrap_exit

    call MPI_FINALIZE(mpi_err)

    return
  end subroutine mpi_wrap_exit

!================================================================================

  subroutine mpi_wrap_msg

    use parameters, only : runname
    implicit none

    integer :: fout

    fout = 33

    if (myid .ne. 0) return
    
    open(fout, file=trim(runname)//'.out', position='append')
    write(fout,*) trim(msg)
    close(fout)

    return
  end subroutine mpi_wrap_msg

!================================================================================

  subroutine mpi_wrap_err

    use parameters, only : runname
    implicit none

    integer :: fout

    fout = 33

    write(*,*) "ERROR (myid=", myid, "):",  trim(msg)

    open(fout, file=trim(runname)//'.out', position='append')
    write(fout,*) "ERROR (myid=", myid, "):",  trim(msg)
    close(fout)
  
    call mpi_abort(MPI_COMM_WORLD, -1, mpi_err)
    stop

  end subroutine mpi_wrap_err


!================================================================================

end module mpi_wrap
